#pragma once
#include<iostream>
#include<string>
#include<jsoncpp/json/json.h>
using namespace std;
const string blank_sapce_sep=" ";
const string protocol_sep="\n";
//#define MySelf 1


string encode(string &content)     //"9"\n"7 + 9"\n
{

string package=to_string(content.size());
package+=protocol_sep;
package+=content;
package+=protocol_sep;

return package;
}

bool decode(string &package,string* content)  // "9"\n"7 + 9"\n
{

size_t pos=package.find(protocol_sep);
if(pos==string::npos)
{
return false;
}
string len_str=package.substr(0,pos);
int len =stoi(len_str);

size_t total_len=len+2+len_str.size();
if(package.size()<total_len)
return false;


*content=package.substr(pos+1,len);
package.erase(0,total_len);
return true;

}

class Request
{
public:
Request(int data1,int data2,char oper)
:x(data1)
,y(data2)
,op(oper)
{
   
}
Request()
{

}


bool Serialize(string *out)//"z + b"
{
#ifdef MySelf 
string s=to_string(x);
s+=blank_sapce_sep;
s+=op;
s+=blank_sapce_sep;
s+=to_string(y);
*out=s;
return true;
#else
    Json::Value root;
    root["x"]=x;
    root["y"]=y;
    root["op"]=op;

    Json::FastWriter w;
   //Json::StyledWriter w;
    *out=w.write(root);
    return true;

#endif
}
bool Deserialize(string & in)
{
#ifdef MySelf 
size_t left=in.find(blank_sapce_sep);
if(left==string::npos)
{
   return false;
}
string part_x=in.substr(0,left);
size_t right=in.rfind(blank_sapce_sep);
if(right==string::npos)
{return false;}
string part_y=in.substr(right+1);
if(left+2!=right)
  return false;

 op=in[left+1];
x=stoi(part_x);
y=stoi(part_y);
return true;
#else
     Json::Value root;
     Json::Reader r;
     r.parse(in,root);
     x=root["x"].asInt();
     y=root["y"].asInt();
     op=root["op"].asInt();
     return true;

#endif



}

public:
int x;
int y;
char op;
};


class Response
{
public:
Response(int res,int c)
:result(res)
,code(c)
{
   


}
Response()
{


}

bool Serialize(string *out)//变"result code"
{
#ifdef MySelf 
string s=to_string(result);
s+=blank_sapce_sep;
s+=to_string(code);
*out=s;
return true;
#else
    Json::Value root;
    root["result"]=result;
    root["code"]=code;
   

    Json::FastWriter w;
  // Json::StyledWriter w;
    *out=w.write(root);
     return true;
#endif
}
void deprint()
{
cout<<"result:"<<result<<"code:"<<code<<endl;

}




bool Deserialize(string & in)//"result code"搞散
{
   #ifdef MySelf
size_t left=in.find(blank_sapce_sep);
if(left==string::npos)
{
return false;
}
string part_result=in.substr(0,left);
string part_code=in.substr(left+1);
result=stoi(part_result);
code=stoi(part_code);
return true;
#else
     Json::Value root;
     Json::Reader r;
     r.parse(in,root);
    result=root["result"].asInt();
    code=root["code"].asInt();
  
     return true;




#endif
}

public:
int result;
int code;
};